package com.yangyang.ralearn.common.entity.base;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import com.yangyang.ralearn.common.Constants;
import com.yangyang.ralearn.common.JEnvironment;
import com.yangyang.ralearn.common.entity.domain.RobotPredicate;
import com.yangyang.ralearn.common.types.JObject;

public class BasePredicate implements Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1976249222048688332L;
	protected String type;
	protected List<JObject> paramValues;
	protected JEnvironment environment;

	public String getName() {
		return this.type;
	}

	public void setName(String name) {
		this.type = name;
	}

	public BasePredicate(JEnvironment environment, String name,
			JObject... array) {
		this.environment = environment;
		this.type = name;
		this.paramValues = new ArrayList<JObject>();
		if (array != null)
			for (int i = 0; i < array.length; i++) {
				paramValues.add(array[i]);
			}
	}

	@Override
	public boolean equals(Object obj) {
		BasePredicate bp = (BasePredicate) obj;
		if (bp == null)
			return false;

		BasePredicateDef def = environment.mapNamePredicateDef.get(bp.type
				.startsWith(Constants.NEG_PREFIX) ? bp.type.substring(1)
				: bp.type);
		if (def == null) {
			System.err
					.println("error while get the predicatedef for predicate "
							+ bp);
			assert (false);
		} else {
			boolean result = this.type.equals(bp.type);
			if (def.posSensitive) {
				for (int i = 0; i < this.getPraramValues().size() && result; i++) {
					result &= this.getPraramValues().get(i)
							.equals(bp.getPraramValues().get(i));
				}
			} else {
				for (int i = 0; i < this.getPraramValues().size() && result; i++) {
					result &= this.getPraramValues().contains(
							bp.getPraramValues().get(i));
				}
			}
			return result;
		}
		return false;
	}

	/**
	 * abstract class
	 * 
	 * @param line
	 * @return
	 */
	// 根据字符串parse一个predicate
	public static AbstractDomainPredicate parsePredicate(
			JEnvironment environment, String line) {
		return parsePredicate(environment, line.split(" "));
	};

	public static AbstractDomainPredicate parsePredicate(
			JEnvironment environment, String[] array) {
		JObject[] object = new JObject[array.length - 1];
		for (int i = 1; i < array.length; i++) {
			object[i - 1] = environment.mapName2Object.get(array[i]);
		}
		return new RobotPredicate(environment, array[0], object);
	}

	/**
	 * @return the mParameters
	 */
	public List<JObject> getPraramValues() {
		return paramValues;
	}

	@Override
	public String toString() {
		return "BasePredicate [type=" + type + ", paramValues=" + paramValues
				+ "]";
	}

	@Override
	public int hashCode() {
		// TODO Auto-generated method stub
		return type.hashCode();
	}
}
